package cn.com.zcode.core.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import ognl.DefaultTypeConverter;

public class DateConverter extends DefaultTypeConverter {

	private static final DateFormat[] ACCEPT_DATE_FORMATS = { new SimpleDateFormat("dd/MM/yyyy"), new SimpleDateFormat("yyyy-MM-dd"), new SimpleDateFormat("yyyy/MM/dd") }; // 支持转换的日期格式

	@Override
	@SuppressWarnings("rawtypes")
	public Object convertValue(Map context, Object value, Class toType) {
		if (toType == Date.class) {
			String[] params = (String[]) value;
			String dateString = params[0];
			for (DateFormat format : ACCEPT_DATE_FORMATS) {

				try {
					return format.parse(dateString);
				} catch (ParseException e) {
					continue;

				}

			}
		} else if (toType == String.class) {
			Date date = (Date) value;
			return ACCEPT_DATE_FORMATS[0].format(date);

		}
		return null;
	}

}
